<!-- 电表挂表： 用于电表和公区能源费的电表 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">挂表</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">{{ firstTitle }}</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm v-show="pageType == 'publicArea'" :filed-list="materBaseEquipment" ref="equipmentForm" :isDisabled="isReadOnly"></HsForm>
						<HsForm v-show="pageType != 'publicArea'" :filed-list="breakSignContract" ref="contractForm" :isDisabled="isReadOnly"></HsForm>
					</div>
					<!-- card2 -->
					<div class="zs-align-center zs-space-bottom zs-space-top-lg" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">电表信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm :filed-list="breakSignInfoList" ref="baseForm" :isDisabled="isReadOnly" @selectChange="selectChange" @remoteMethod="remoteMethod"></HsForm>
					</div>
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import HsForm from '@/components/hsForm.vue';
	import { breakSignContract, breakSignInfo, breakSignEleInfo, materBaseEquipment } from '@/config/form/energy.js';
	import { electricitySignSaveApi, eAreaSignApi, electricityMeterSourceApi, electricityMeterSettingInfoApi } from '@/api/energy.js';
	import { ElMessage } from 'element-plus';
	import { ref, nextTick, watch, reactive, computed } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { setFormSelectOptions } from '@/utils/formEvent';
	import { deepClone } from '@/utils/publicUtils';
	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		pageType: { type: String, default: '' },
		currentRow: { type: Object },
	});
	const emit = defineEmits(['close']);
	const route = useRoute();
	const store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	let firstTitle = computed(() => {
		return props.pageType == 'publicArea' ? '电表信息' : '合同信息';
	});
	const curNodeList = ref([
		{ name: firstTitle, id: 'sm-drawer-demo-card-01' },
		{ name: '电表信息', id: 'sm-drawer-demo-card-02' },
	]);

	let isShowDrawer = ref(props.isShow);
	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && initForm();
			});
		},
	);

	const contractForm = ref();
	const equipmentForm = ref();
	const baseForm = ref();

	//提交
	const doConfirm = async () => {
		let model = await baseForm.value.validateForm();
		if (!model) return;
		if (props.pageType == 'publicArea') {
			model.commonAreaMeterId = props.currentRow.id;
		} else {
			model.contractId = props.currentRow.contractId;
			model.contractCode = props.currentRow.contractCode;
			model.brandName = props.currentRow.brandName;
			model.assetsPromoteNum = props.currentRow.assetsPromoteNum;
			model.projectCode = route.query.projectCode;
		}
		let res = props.pageType == 'publicArea' ? await eAreaSignApi(model) : await electricitySignSaveApi(model);
		if (res.data.code == 200) {
			ElMessage({
				message: '提交成功',
				type: 'success',
			});
			isShowDrawer.value = false;
			emit('close', { isShow: false, isRefresh: true });
		}
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//表单初始化
	let breakSignInfoList = ref(deepClone([...breakSignEleInfo, ...breakSignInfo]));
	const initForm = () => {
		if (props.pageType == 'publicArea') {
			getEqipmentInfo();
		}
		getSourceMeterList();
		breakSignInfoList.value.forEach(item => {
			if (['coefficient'].includes(item.bindFieldName)) {
				item.isDisabled = false;
			}
			if (['meterReading', 'electricMeterId'].includes(item.bindFieldName)) {
				item.isHide = false;
			}
		});
		contractForm.value.setFiledVal(props.currentRow);
		baseForm.value.resetFields();
	};

	//设置某些字段为disabled isRequired
	const setMeterReadingDisabledStatus = (list, isDisabled, filedList, isRequired) => list.map(item => (filedList.includes(item.bindFieldName) ? { ...item, isDisabled, isRequired } : item));

	//表单关联
	const selectChange = data => {
		// 智能表， 不管是预付费还是后付费的  预付费表，不管是智能表还是普通表， 都是用新的解表逻辑
		if (data.filedName == 'electricMeterId') {
			let target = sourceMeterList.value.find(item => item.electricMeterId == data.filedVal);
			if (target) {
				delete target.coefficient;
				baseForm.value.setFiledVal(target);
				if (props.pageType == 'publicArea') {
					const isDisabled = target.electricMeterModel == 2 || target.electricMeterType == 1;
					breakSignInfoList.value = setMeterReadingDisabledStatus(breakSignInfoList.value, isDisabled, ['meterReading'], !isDisabled);
					isDisabled && baseForm.value.setFiledSource('meterReading', 0);
				} else {
					const isDisabled = target.electricMeterModel == 2;
					breakSignInfoList.value = setMeterReadingDisabledStatus(breakSignInfoList.value, isDisabled, ['meterReading', 'coefficient'], !isDisabled);
					isDisabled && baseForm.value.setFiledSource('meterReading', '');
					isDisabled && baseForm.value.setFiledSource('coefficient', 1);
				}
			}
		}
	};

	//联想查询
	const remoteMethod = data => {
		if (data.remoteVal) {
			getSourceMeterList(data.remoteVal);
		}
	};

	//设备详情
	const getEqipmentInfo = async () => {
		let res = await electricityMeterSettingInfoApi(props.currentRow.deviceId);
		if (res.data.code != 200) return;
		let resData = Object.assign(res.data.data);
		initData(resData);
		equipmentForm.value.setFiledVal(resData);
	};

	const initData = data => {
		data.deviceStatusDict = String(data.deviceStatusDict);
		data.effectState = diffDate(data.warrantyStartTime, data.warrantyEndTime, 'effectState');
		data.lifeEffectState = diffDate(data.lifeStartTime, data.lifeEndTime, 'lifeEffectState');
		data.multiplier = data.multiplier ? data.multiplier : 1;
	};

	// 设置有效期
	const diffDate = (startDate, endDate, targetFiled) => {
		let nowTime = new Date().getTime();
		if (startDate <= nowTime && nowTime <= endDate) {
			return targetFiled == 'effectState' ? '质保期内' : '寿命期内';
		} else {
			return targetFiled == 'effectState' ? '质保期外' : '寿命期外';
		}
	};

	//电表数据源
	let sourceMeterList = ref([]);
	const getSourceMeterList = async electricMeterCode => {
		let params = { projectCode: route.query.projectCode, type: props.pageType == 'publicArea' ? 2 : 1, commonAreaMeterId: props.currentRow.id, electricMeterCode: electricMeterCode };
		if (props.pageType != 'publicArea') params.contractCode = props.currentRow.contractCode;
		let res = await electricityMeterSourceApi(params);
		if (res.data.code !== 200) return;
		sourceMeterList.value = res.data.data || [];
		setFormSelectOptions(breakSignInfoList.value, 'electricMeterId', res.data.data);
	};
</script>
